package com.longbo.leaf.security;

import com.longbo.leaf.common.BaseException;
import com.longbo.leaf.common.Status;
import com.longbo.leaf.portal.mapper.PermissionMapper;
import com.longbo.leaf.portal.mapper.RoleMapper;
import com.longbo.leaf.portal.mapper.UserMapper;
import com.longbo.leaf.portal.model.Permission;
import com.longbo.leaf.portal.model.Role;
import com.longbo.leaf.portal.model.User;
import com.longbo.leaf.vo.UserPrincipal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("UserDetailsServiceImpl.loadUserByUsername");
        //根据username查询用户详情,先查询用户是否存在,不存在抛出异常
        User user = userMapper.findUserByUsername(username).orElseThrow(()->new BaseException(Status.USER_HAS_EXIST));
        List<Role> roles = roleMapper.selectRoleByUserId(user.getId());
        List<Long> roleIds = roles.stream()
                .map(Role::getId)
                .collect(Collectors.toList());
        System.out.println("UserDetailsServiceImpl.loadUserByUsername");
        List<Permission> permissions = permissionMapper.selectPermissionByRoleIdList(roleIds);
        System.out.println(UserPrincipal.create(user,roles,permissions));
        return UserPrincipal.create(user,roles,permissions);
    }
}
